<!DOCTYPE html>


<html lang="en">


<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    springboot中dubbo服务导出-1 |  一曲秋殇
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/images/myfavicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-dubbo/springboot中dubbo服务导出-1"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  springboot中dubbo服务导出-1
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/dubbo/springboot%E4%B8%ADdubbo%E6%9C%8D%E5%8A%A1%E5%AF%BC%E5%87%BA-1/" class="article-date">
  <time datetime="2021-12-13T05:51:40.041Z" itemprop="datePublished">2021-12-13</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E5%90%8E%E5%8F%B0/">后台</a> / <a class="article-category-link" href="/categories/%E5%90%8E%E5%8F%B0/java/">java</a> / <a class="article-category-link" href="/categories/%E5%90%8E%E5%8F%B0/java/dubbo/">dubbo</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">5.1k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">22 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/hint.css/2.4.1/hint.min.css"><blockquote>
<p>dubbo服务导出过程比较复杂，因此分为三篇文章进行分析，这一篇分主要是分析从服务导出触发一直到即将进入RegistryProtocol#export方法执行远程注册相关操作。<br>以下分析是基于dubbo2.7.8</p>
</blockquote>
<p>  整个过程的方法调用栈如下（从下到上）：<br>  <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">export(Invoker):<span class="number">205</span>, RegistryProtocol (org.apache.dubbo.registry.integration), RegistryProtocol.java</span><br><span class="line">export(Invoker):<span class="number">62</span>, ProtocolListenerWrapper (org.apache.dubbo.rpc.protocol), ProtocolListenerWrapper.java</span><br><span class="line">export(Invoker):<span class="number">153</span>, ProtocolFilterWrapper (org.apache.dubbo.rpc.protocol), ProtocolFilterWrapper.java</span><br><span class="line">export(Invoker):<span class="number">64</span>, QosProtocolWrapper (org.apache.dubbo.qos.protocol), QosProtocolWrapper.java</span><br><span class="line">export(Invoker):-<span class="number">1</span>, Protocol$Adaptive (org.apache.dubbo.rpc), Protocol$Adaptive.java</span><br><span class="line">doExportUrlsFor1Protocol(ProtocolConfig, List):<span class="number">492</span>, ServiceConfig (org.apache.dubbo.config), ServiceConfig.java</span><br><span class="line">doExportUrls():<span class="number">325</span>, ServiceConfig (org.apache.dubbo.config), ServiceConfig.java</span><br><span class="line">doExport():<span class="number">300</span>, ServiceConfig (org.apache.dubbo.config), ServiceConfig.java</span><br><span class="line">export():<span class="number">206</span>, ServiceConfig (org.apache.dubbo.config), ServiceConfig.java</span><br><span class="line">lambda$exportServices$<span class="number">15</span>(ServiceConfigBase):<span class="number">1103</span>, DubboBootstrap (org.apache.dubbo.config.bootstrap), DubboBootstrap.java</span><br><span class="line">accept(Object):-<span class="number">1</span>, <span class="number">1979860449</span> (org.apache.dubbo.config.bootstrap.DubboBootstrap$$Lambda$<span class="number">393</span>), Unknown Source</span><br><span class="line">forEach(Consumer):<span class="number">981</span>, HashMap$Values (java.util), HashMap.java</span><br><span class="line">exportServices():<span class="number">1090</span>, DubboBootstrap (org.apache.dubbo.config.bootstrap), DubboBootstrap.java</span><br><span class="line">start():<span class="number">901</span>, DubboBootstrap (org.apache.dubbo.config.bootstrap), DubboBootstrap.java</span><br><span class="line">onContextRefreshedEvent(ContextRefreshedEvent):<span class="number">59</span>, DubboBootstrapApplicationListener (org.apache.dubbo.config.spring.context), DubboBootstrapApplicationListener.java</span><br><span class="line">onApplicationContextEvent(ApplicationContextEvent):<span class="number">52</span>, DubboBootstrapApplicationListener (org.apache.dubbo.config.spring.context), DubboBootstrapApplicationListener.java</span><br><span class="line">onApplicationEvent(ApplicationEvent):<span class="number">40</span>, OneTimeExecutionApplicationContextEventListener (org.apache.dubbo.config.spring.context), OneTimeExecutionApplicationContextEventListener.java</span><br></pre></td></tr></table></figure><br>  整个过程主要干了下面几个事情，接下来进行逐个分析</p>
<h4 id="1-触发DubboBootstrapApplicationListener的监听"><a href="#1-触发DubboBootstrapApplicationListener的监听" class="headerlink" title="1. 触发DubboBootstrapApplicationListener的监听"></a>1. 触发DubboBootstrapApplicationListener的监听</h4><hr>
<p>从2.7.5开始，dubbo通过 DubboBootstrapApplicationListener 监听器监听spring容器 ContextRefreshedEvent 事件的方式来触发服务的导出操作，那么这个监听器是何时被创建的呢？</p>
<h5 id="1-1-DubboBootstrapApplicationListener的添加"><a href="#1-1-DubboBootstrapApplicationListener的添加" class="headerlink" title="1.1 DubboBootstrapApplicationListener的添加"></a>1.1 DubboBootstrapApplicationListener的添加</h5><p>通过查看DubboAutoConfiguration类中的代码可知，是在setApplicationContext设置spring上下文的时候进行添加的，具体代码如下：</p>
<figure class="highlight java"><figcaption><span>DubboAutoConfiguration.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@ConditionalOnProperty(prefix = DUBBO_PREFIX, name = &quot;enabled&quot;, matchIfMissing = true)</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@AutoConfigureAfter(DubboRelaxedBindingAutoConfiguration.class)</span></span><br><span class="line"><span class="meta">@EnableConfigurationProperties(DubboConfigurationProperties.class)</span></span><br><span class="line"><span class="meta">@EnableDubboConfig</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DubboAutoConfiguration</span> <span class="keyword">implements</span> <span class="title">ApplicationContextAware</span>, <span class="title">BeanDefinitionRegistryPostProcessor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 这个bean方法主要是用来扫描dubbo服务并注册到spring容器用的（前提是有配置dubbo.scan.base-packages）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@ConditionalOnProperty(prefix = DUBBO_SCAN_PREFIX, name = BASE_PACKAGES_PROPERTY_NAME)</span></span><br><span class="line">    <span class="meta">@ConditionalOnBean(name = BASE_PACKAGES_BEAN_NAME)</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ServiceClassPostProcessor <span class="title">serviceClassPostProcessor</span><span class="params">(<span class="meta">@Qualifier(BASE_PACKAGES_BEAN_NAME)</span> Set&lt;String&gt; packagesToScan)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ServiceClassPostProcessor(packagesToScan);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setApplicationContext</span><span class="params">(ApplicationContext applicationContext)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (applicationContext <span class="keyword">instanceof</span> ConfigurableApplicationContext) &#123;</span><br><span class="line">            ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;</span><br><span class="line">            DubboLifecycleComponentApplicationListener dubboLifecycleComponentApplicationListener = <span class="keyword">new</span> DubboLifecycleComponentApplicationListener();</span><br><span class="line">            dubboLifecycleComponentApplicationListener.setApplicationContext(applicationContext);</span><br><span class="line">            context.addApplicationListener(dubboLifecycleComponentApplicationListener);</span><br><span class="line">            <span class="comment">//添加dubboBootstrapApplicationListener监听器到spring中</span></span><br><span class="line">            DubboBootstrapApplicationListener dubboBootstrapApplicationListener = <span class="keyword">new</span> DubboBootstrapApplicationListener();</span><br><span class="line">            dubboBootstrapApplicationListener.setApplicationContext(applicationContext);</span><br><span class="line">            context.addApplicationListener(dubboBootstrapApplicationListener);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>DubboBootstrapApplicationListener监听器的构造方法如下，它会去获取一个单例DubboBootstrap对象设置到dubboBootstrap属性中</p>
<figure class="highlight java"><figcaption><span>DubboBootstrapApplicationListener.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">DubboBootstrapApplicationListener</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.dubboBootstrap = DubboBootstrap.getInstance();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="1-2-DubboBootstrap实例化"><a href="#1-2-DubboBootstrap实例化" class="headerlink" title="1.2 DubboBootstrap实例化"></a>1.2 DubboBootstrap实例化</h5><figure class="highlight java"><figcaption><span>DubboBootstrap.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="title">DubboBootstrap</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">//通过FrameworkExt类型的拓展加载器加载key为&quot;config&quot;的拓展（ConfigManager），这个对象主要用来管理所有的配置，具体见下面分析</span></span><br><span class="line">    configManager = ApplicationModel.getConfigManager();</span><br><span class="line">    <span class="comment">//通过FrameworkExt类型的拓展加载器加载key为&quot;environment&quot;的拓展（Environment）</span></span><br><span class="line">    environment = ApplicationModel.getEnvironment();</span><br><span class="line">    <span class="comment">//注册销毁时的钩子函数</span></span><br><span class="line">    DubboShutdownHook.getDubboShutdownHook().register();</span><br><span class="line">    ShutdownHookCallbacks.INSTANCE.addCallback(<span class="keyword">new</span> ShutdownHookCallback() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">callback</span><span class="params">()</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">            DubboBootstrap.<span class="keyword">this</span>.destroy();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;    </span><br></pre></td></tr></table></figure>
<h5 id="1-3-关于ConfigManager-实例"><a href="#1-3-关于ConfigManager-实例" class="headerlink" title="1.3 关于ConfigManager 实例"></a>1.3 关于ConfigManager 实例</h5><p>上面1.2 中 DubboBootstrap 构造的第3行通过<code>ApplicationModel.getConfigManager()</code>获取了ConfigManager对象保存在DubboBootstrap属性中<br>ApplicationModel.getConfigManager()方法的代码如下：</p>
<figure class="highlight java"><figcaption><span>ApplicationModel.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ConfigManager <span class="title">getConfigManager</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> (ConfigManager) LOADER.getExtension(ConfigManager.NAME);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>主要是通过FrameworkExt类型的拓展加载器加载key为”config”的拓展，这个config默认扩展就是ConfigManager，所以通过<code>ApplicationModel.getConfigManager()</code>每次获取的都是同一个单例ConfigManager对象<br>这个对象主要是用来管理所有的配置的，包括我们配置的应用名称，注册中心地址及@Service注解标注的dubbo服务等都会被添加到这个配置管理器中，下面来具体看看这些配置是怎么被添加进去的</p>
<h5 id="1-3-1-应用名等配置何时添加到ConfigManager-实例"><a href="#1-3-1-应用名等配置何时添加到ConfigManager-实例" class="headerlink" title="1.3.1 应用名等配置何时添加到ConfigManager 实例"></a>1.3.1 应用名等配置何时添加到ConfigManager 实例</h5><p>在DubboAutoConfiguration上有一个@EnableDubboConfig注解，该注解@Import了DubboConfigConfigurationRegistrar这个类</p>
<figure class="highlight java"><figcaption><span>DubboConfigConfigurationRegistrar.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DubboConfigConfigurationRegistrar</span> <span class="keyword">implements</span> <span class="title">ImportBeanDefinitionRegistrar</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerBeanDefinitions</span><span class="params">(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry)</span> </span>&#123;</span><br><span class="line">        AnnotationAttributes attributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableDubboConfig.class.getName()));</span><br><span class="line">        <span class="keyword">boolean</span> multiple = attributes.getBoolean(<span class="string">&quot;multiple&quot;</span>);</span><br><span class="line">        <span class="comment">// 注册DubboConfigConfiguration.Single.class中的那些bean</span></span><br><span class="line">        registerBeans(registry, DubboConfigConfiguration.Single.class);</span><br><span class="line">        <span class="keyword">if</span> (multiple) &#123; </span><br><span class="line">            registerBeans(registry, DubboConfigConfiguration.Multiple.class);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// Since 2.7.6</span></span><br><span class="line">        registerCommonBeans(registry);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的第7行registerBeans会去读取DubboConfigConfiguration.Single.class类注解中添加的那些配置，然后去加载符合要求的相关bean<br>DubboConfigConfiguration.Single.class类的代码如下：</p>
<figure class="highlight java"><figcaption><span>DubboConfigConfiguration.Single.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DubboConfigConfiguration</span> </span>&#123;</span><br><span class="line">    <span class="meta">@EnableConfigurationBeanBindings(&#123;</span></span><br><span class="line"><span class="meta">            @EnableConfigurationBeanBinding(prefix = &quot;dubbo.application&quot;, type = ApplicationConfig.class),</span></span><br><span class="line"><span class="meta">            @EnableConfigurationBeanBinding(prefix = &quot;dubbo.module&quot;, type = ModuleConfig.class),</span></span><br><span class="line"><span class="meta">            @EnableConfigurationBeanBinding(prefix = &quot;dubbo.registry&quot;, type = RegistryConfig.class),</span></span><br><span class="line"><span class="meta">            @EnableConfigurationBeanBinding(prefix = &quot;dubbo.protocol&quot;, type = ProtocolConfig.class),</span></span><br><span class="line"><span class="meta">            @EnableConfigurationBeanBinding(prefix = &quot;dubbo.monitor&quot;, type = MonitorConfig.class),</span></span><br><span class="line"><span class="meta">            @EnableConfigurationBeanBinding(prefix = &quot;dubbo.provider&quot;, type = ProviderConfig.class),</span></span><br><span class="line"><span class="meta">            @EnableConfigurationBeanBinding(prefix = &quot;dubbo.consumer&quot;, type = ConsumerConfig.class),</span></span><br><span class="line"><span class="meta">            @EnableConfigurationBeanBinding(prefix = &quot;dubbo.config-center&quot;, type = ConfigCenterBean.class),</span></span><br><span class="line"><span class="meta">            @EnableConfigurationBeanBinding(prefix = &quot;dubbo.metadata-report&quot;, type = MetadataReportConfig.class),</span></span><br><span class="line"><span class="meta">            @EnableConfigurationBeanBinding(prefix = &quot;dubbo.metrics&quot;, type = MetricsConfig.class),</span></span><br><span class="line"><span class="meta">            @EnableConfigurationBeanBinding(prefix = &quot;dubbo.ssl&quot;, type = SslConfig.class)</span></span><br><span class="line"><span class="meta">    &#125;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Single</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里面的这些配置都继承自AbstractConfig，在AbstractConfig中有个addIntoConfigManager方法，该方法标注有@PostConstruct注解，代码如下</p>
<figure class="highlight java"><figcaption><span>AbstractConfig.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@PostConstruct</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addIntoConfigManager</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    ApplicationModel.getConfigManager().addConfig(<span class="keyword">this</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>所以继承自AbstractConfig的bean初始化的时候都会调用ApplicationModel.getConfigManager().addConfig方法将配置添加到ConfigManager对象中</p>
<h5 id="1-3-2-dubbo服务类配置何时添加到ConfigManager-实例"><a href="#1-3-2-dubbo服务类配置何时添加到ConfigManager-实例" class="headerlink" title="1.3.2 dubbo服务类配置何时添加到ConfigManager 实例"></a>1.3.2 dubbo服务类配置何时添加到ConfigManager 实例</h5><p>同样是在DubboAutoConfiguration中定义了一个ServiceClassPostProcessor类型的bean，该bean的加载条件是有dubbo.scan.base-packages配置<br>该类实现了BeanDefinitionRegistryPostProcessor接口</p>
<figure class="highlight java"><figcaption><span>ServiceClassPostProcessor.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">postProcessBeanDefinitionRegistry</span><span class="params">(BeanDefinitionRegistry registry)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line"> </span><br><span class="line">     <span class="comment">// @since 2.7.5</span></span><br><span class="line">     registerInfrastructureBean(registry, DubboBootstrapApplicationListener.BEAN_NAME, DubboBootstrapApplicationListener.class);</span><br><span class="line"> </span><br><span class="line">     Set&lt;String&gt; resolvedPackagesToScan = resolvePackagesToScan(packagesToScan);</span><br><span class="line"> </span><br><span class="line">     <span class="keyword">if</span> (!CollectionUtils.isEmpty(resolvedPackagesToScan)) &#123;</span><br><span class="line">         registerServiceBeans(resolvedPackagesToScan, registry);</span><br><span class="line">     &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">         <span class="keyword">if</span> (logger.isWarnEnabled()) &#123;</span><br><span class="line">             logger.warn(<span class="string">&quot;packagesToScan is empty , ServiceBean registry will be ignored!&quot;</span>);</span><br><span class="line">         &#125;</span><br><span class="line">     &#125;</span><br><span class="line"> </span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>在ServiceClassPostProcessor bean被加载的时候会去加载dubbo.scan.base-packages配置下的那些dubbo服务bean定义<br>ServiceClassPostProcessor#buildServiceBeanDefinition方法会将我们自己定义的dubbo服务bean定义构建成ServiceBean定义，而ServiceBean继承自AbstractConfig，所以在服务bean被初始化的时候会调用 ApplicationModel.getConfigManager().addConfig(this);</p>
<h4 id="2-监听方法中调用-DubboBootstrap-start"><a href="#2-监听方法中调用-DubboBootstrap-start" class="headerlink" title="2. 监听方法中调用 DubboBootstrap#start()"></a>2. 监听方法中调用 DubboBootstrap#start()</h4><hr>
<p>在1中 DubboBootstrapApplicationListener 监听器事件方法被触发后会执行DubboBootstrap#start()方法</p>
<figure class="highlight java"><figcaption><span>DubboBootstrap.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> DubboBootstrap <span class="title">start</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">//此处用cas操作保证start方法的逻辑只会被执行一次</span></span><br><span class="line">    <span class="keyword">if</span> (started.compareAndSet(<span class="keyword">false</span>, <span class="keyword">true</span>)) &#123;</span><br><span class="line">        ready.set(<span class="keyword">false</span>);</span><br><span class="line">        <span class="comment">//一些初始化操作，方法具体内容下面下面有贴出</span></span><br><span class="line">        initialize();</span><br><span class="line">        <span class="comment">//重点：服务导出，该方法中会循环导出服务</span></span><br><span class="line">        exportServices();</span><br><span class="line">        <span class="keyword">if</span> (!isOnlyRegisterProvider() || hasExportedServices()) &#123;</span><br><span class="line">            exportMetadataService();</span><br><span class="line">            registerServiceInstance();</span><br><span class="line">        &#125;</span><br><span class="line">        referServices();</span><br><span class="line">        <span class="keyword">if</span> (asyncExportingFutures.size() &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">new</span> Thread(() -&gt; &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    <span class="keyword">this</span>.awaitFinish();</span><br><span class="line">                &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                &#125;</span><br><span class="line">                ready.set(<span class="keyword">true</span>);</span><br><span class="line">            &#125;).start();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            ready.set(<span class="keyword">true</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="2-1-调用initialize方法执行配置中心等初始化"><a href="#2-1-调用initialize方法执行配置中心等初始化" class="headerlink" title="2.1 调用initialize方法执行配置中心等初始化"></a>2.1 调用initialize方法执行配置中心等初始化</h5><p>initialize方法代码如下</p>
<figure class="highlight java"><figcaption><span>DubboBootstrap.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">initialize</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!initialized.compareAndSet(<span class="keyword">false</span>, <span class="keyword">true</span>)) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//此处主要是初始化FrameworkExt类型的三个拓展config、environment和repository并执循环执行拓展的initialize方法（其中config、environment这两个拓展在1.2实例化DubboBootstrap时候已经被加载了）</span></span><br><span class="line">    ApplicationModel.initFrameworkExts();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//启动配置中心，默认配置中心为zookeeper，详见2.1.1</span></span><br><span class="line">    startConfigCenter();</span><br><span class="line">    <span class="comment">//详见2.1.1</span></span><br><span class="line">    loadRemoteConfigs();</span><br><span class="line"></span><br><span class="line">    checkGlobalConfigs();</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//启动元数据中心，默认为zookeeper，详见2.1.3</span></span><br><span class="line">    startMetadataCenter();</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//根据metadata-type值初始化对应的MetadataService拓展实现，local对应的是InMemoryWritableMetadataService，remote对应的是RemoteWritableMetadataService</span></span><br><span class="line">    <span class="comment">//MetadataService主要是提供元数据的写入，和发布等功能，像RemoteWritableMetadataService#publishProviderServiceDefinition方法里面通过调用上面startMetadataCenter()方法中初始化好的MetadataReport对象提供将元数据写入到远程元数据中心的能力，而RemoteWritableMetadataService的写入等操作是委托给了InMemoryWritableMetadataService</span></span><br><span class="line">    <span class="comment">//在有配置元数据中心的情况下，每个接口服务暴露完成后都会将接口的元数据发布到元数据中心，详情可查看2.2.3末尾部分的代码</span></span><br><span class="line">    initMetadataService();</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//初始化那些支持的MetadataServiceExporter拓展实现，local对应的是ConfigurableMetadataServiceExporter，remote对应的是RemoteMetadataServiceExporter</span></span><br><span class="line">    <span class="comment">//MetadataServiceExporter主要是2.7.5新提供的特性，用于支持服务自省，将MetadataService服务以dubbo业务接口服务的形式进行暴露（选用的是一个随机接口），详细可查看dubbo服务自省章节</span></span><br><span class="line">    initMetadataServiceExports();</span><br><span class="line">    </span><br><span class="line">    initEventListener();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h6 id="2-1-1-startConfigCenter连接配置中心加载数据"><a href="#2-1-1-startConfigCenter连接配置中心加载数据" class="headerlink" title="2.1.1 startConfigCenter连接配置中心加载数据"></a>2.1.1 startConfigCenter连接配置中心加载数据</h6><p>先来看下配置中心相关的类关系图（<a target="_blank" rel="noopener" href="https://www.processon.com/view/link/6066bd15e0b34d282990076b">原图链接</a>）：<br><img src="http://img.luobiao.vip/img/20210402144216.png"></p>
<p>startConfigCenter方法代码如下：</p>
<figure class="highlight java"><figcaption><span>DubboBootstrap.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">startConfigCenter</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    useRegistryAsConfigCenterIfNecessary();</span><br><span class="line">    <span class="comment">//获取配置中心列表，默认配置中心为zookeeper</span></span><br><span class="line">    Collection&lt;ConfigCenterConfig&gt; configCenters = configManager.getConfigCenters();</span><br><span class="line">    <span class="keyword">if</span> (CollectionUtils.isEmpty(configCenters)) &#123;</span><br><span class="line">        ConfigCenterConfig configCenterConfig = <span class="keyword">new</span> ConfigCenterConfig();</span><br><span class="line">        configCenterConfig.refresh();</span><br><span class="line">        <span class="keyword">if</span> (configCenterConfig.isValid()) &#123;</span><br><span class="line">            configManager.addConfigCenter(configCenterConfig);</span><br><span class="line">            configCenters = configManager.getConfigCenters();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">//循环配置中心列表</span></span><br><span class="line">        <span class="keyword">for</span> (ConfigCenterConfig configCenterConfig : configCenters) &#123;</span><br><span class="line">            <span class="comment">//将Environment中的属性设置到ConfigCenterBean对象的属性</span></span><br><span class="line">            <span class="comment">//默认情况下配置优先级如下（默认情况情况下配置中心优先级高于本地，可通过highest-priority设置）</span></span><br><span class="line">            <span class="comment">//系统配置属性 &gt; 配置中心应用配置 &gt; 配置中心全局配置 &gt; ServiceConfig 等编程接口采集的配置 &gt; 本地配置文件配置</span></span><br><span class="line">            configCenterConfig.refresh();</span><br><span class="line">            ConfigValidationUtils.validateConfigCenterConfig(configCenterConfig);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (CollectionUtils.isNotEmpty(configCenters)) &#123;</span><br><span class="line">        CompositeDynamicConfiguration compositeDynamicConfiguration = <span class="keyword">new</span> CompositeDynamicConfiguration();</span><br><span class="line">        <span class="comment">//循环配置中心列表将加载的每个配置中心返回的DynamicConfiguration对象添加到组合对象CompositeDynamicConfiguration中，最终添加到环境变量中</span></span><br><span class="line">        <span class="keyword">for</span> (ConfigCenterConfig configCenter : configCenters) &#123;</span><br><span class="line">            <span class="comment">//prepareEnvironment方法中会去加载对应的配置中心并将配置中心的配置更新到环境变量中（还会对配置中心跟路径添加监听）</span></span><br><span class="line">            <span class="comment">//最后返回CompositeDynamicConfiguration对象添加到compositeDynamicConfiguration，prepareEnvironment方法详细逻辑下面再展开</span></span><br><span class="line">            compositeDynamicConfiguration.addConfiguration(prepareEnvironment(configCenter));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//添加组合对象compositeDynamicConfiguration到环境变量中，</span></span><br><span class="line">        environment.setDynamicConfiguration(compositeDynamicConfiguration);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//在加载完远程配置中心的配置后重新刷新配置到ApplicationConfig、MonitorConfig、ModuleConfig、ProtocolConfig、RegistryConfig、ProviderConfig、ConsumerConfig。这些配置中</span></span><br><span class="line">    configManager.refreshAll();</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>prepareEnvironment方法代码如下：</p>
<figure class="highlight java"><figcaption><span>DubboBootstrap.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> DynamicConfiguration <span class="title">prepareEnvironment</span><span class="params">(ConfigCenterConfig configCenter)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (configCenter.isValid()) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!configCenter.checkOrUpdateInited()) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//通过配置url加载远程配置中心，比如url的协议为zookeeper，则会通过自适应拓展最终会返回一个ZookeeperDynamicConfiguration对象，并且会添加对/dubbo/config目录的监听</span></span><br><span class="line">        DynamicConfiguration dynamicConfiguration = getDynamicConfiguration(configCenter.toUrl());</span><br><span class="line">        <span class="comment">//通过上一步获取的dynamicConfiguration获取全局配置中心的配置内容</span></span><br><span class="line">        <span class="comment">//默认情况下是从/dubbo/config/dubbo/dubbo.properties加载</span></span><br><span class="line">        <span class="comment">//第一个dubbo是命名空间（可通过dubbo.config-center.namespace），config为固定值，第二个dubbo为配置中心默认组名称（可通过dubbo.config-center.group）指定，dubbo.properties为文件（可通过dubbo.config-center.config-file指定）</span></span><br><span class="line">        String configContent = dynamicConfiguration.getProperties(configCenter.getConfigFile(), configCenter.getGroup());</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取应用名称作为应用配置中心的组名</span></span><br><span class="line">        String appGroup = getApplication().getName();</span><br><span class="line">        String appConfigContent = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">if</span> (isNotEmpty(appGroup)) &#123;</span><br><span class="line">            <span class="comment">//如果没用通过dubbo.config-center.app-config-file指定应用配置文件，则为默认的dubbo.properties，最终读取的应用配置中心路径为/dubbo/config/应用名称/dubbo.properties</span></span><br><span class="line">            appConfigContent = dynamicConfiguration.getProperties</span><br><span class="line">                    (isNotEmpty(configCenter.getAppConfigFile()) ? configCenter.getAppConfigFile() : configCenter.getConfigFile(),</span><br><span class="line">                            appGroup</span><br><span class="line">                    );</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            environment.setConfigCenterFirst(configCenter.isHighestPriority());</span><br><span class="line">            <span class="comment">//更新环境变量中全局配置</span></span><br><span class="line">            environment.updateExternalConfigurationMap(parseProperties(configContent));</span><br><span class="line">            <span class="comment">//更新环境变量中应用配置</span></span><br><span class="line">            environment.updateAppExternalConfigurationMap(parseProperties(appConfigContent));</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">&quot;Failed to parse configurations from Config Center.&quot;</span>, e);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> dynamicConfiguration;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h6 id="2-1-2-解析配置中心的多注册中心和多协议配置"><a href="#2-1-2-解析配置中心的多注册中心和多协议配置" class="headerlink" title="2.1.2 解析配置中心的多注册中心和多协议配置"></a>2.1.2 解析配置中心的多注册中心和多协议配置</h6><p>这一步主要是判断2.1.1中加载的配置中心配置是否有dubbo.registries.（多注册中心）和dubbo.protocols.（多协议）开头的配置，有的话解析添加到ConfigManager中进行缓存</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">loadRemoteConfigs</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    List&lt;RegistryConfig&gt; tmpRegistries = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="comment">//解析externalConfigurationMap和appExternalConfigurationMap中多注册中心配置（查找是否有dubbo.registries.前缀的配置）</span></span><br><span class="line">    Set&lt;String&gt; registryIds = configManager.getRegistryIds();</span><br><span class="line">    registryIds.forEach(id -&gt; &#123;</span><br><span class="line">        <span class="keyword">if</span> (tmpRegistries.stream().noneMatch(reg -&gt; reg.getId().equals(id))) &#123;</span><br><span class="line">            tmpRegistries.add(configManager.getRegistry(id).orElseGet(() -&gt; &#123;</span><br><span class="line">                RegistryConfig registryConfig = <span class="keyword">new</span> RegistryConfig();</span><br><span class="line">                registryConfig.setId(id);</span><br><span class="line">                registryConfig.refresh();</span><br><span class="line">                <span class="keyword">return</span> registryConfig;</span><br><span class="line">            &#125;));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">    configManager.addRegistries(tmpRegistries);</span><br><span class="line">    List&lt;ProtocolConfig&gt; tmpProtocols = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="comment">//解析externalConfigurationMap和appExternalConfigurationMap中多协议配置（查找是否有dubbo.protocols.前缀的配置）</span></span><br><span class="line">    Set&lt;String&gt; protocolIds = configManager.getProtocolIds();</span><br><span class="line">    protocolIds.forEach(id -&gt; &#123;</span><br><span class="line">        <span class="keyword">if</span> (tmpProtocols.stream().noneMatch(prot -&gt; prot.getId().equals(id))) &#123;</span><br><span class="line">            tmpProtocols.add(configManager.getProtocol(id).orElseGet(() -&gt; &#123;</span><br><span class="line">                ProtocolConfig protocolConfig = <span class="keyword">new</span> ProtocolConfig();</span><br><span class="line">                protocolConfig.setId(id);</span><br><span class="line">                protocolConfig.refresh();</span><br><span class="line">                <span class="keyword">return</span> protocolConfig;</span><br><span class="line">            &#125;));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">    configManager.addProtocols(tmpProtocols);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h6 id="2-1-3-启动元数据中心"><a href="#2-1-3-启动元数据中心" class="headerlink" title="2.1.3 启动元数据中心"></a>2.1.3 启动元数据中心</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">startMetadataCenter</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    useRegistryAsMetadataCenterIfNecessary();</span><br><span class="line"></span><br><span class="line">    ApplicationConfig applicationConfig = getApplication();</span><br><span class="line">    <span class="comment">//application.metadata-type配置的值</span></span><br><span class="line">    String metadataType = applicationConfig.getMetadataType();</span><br><span class="line">    <span class="comment">//获取元数据中心配置，虽然使用集合接收多个元数据中心配置，但从后面的代码可以看出是不支持多元数据中心的</span></span><br><span class="line">    Collection&lt;MetadataReportConfig&gt; metadataReportConfigs = configManager.getMetadataConfigs();</span><br><span class="line">    <span class="keyword">if</span> (CollectionUtils.isEmpty(metadataReportConfigs)) &#123;</span><br><span class="line">        <span class="comment">//如果配置的元数据类型为remote但又没有配置元数据中心的话是会抛出错误的（在使用zookeeper作为注册中心的时候默认是会使用zookeeper作为元数据中心的）</span></span><br><span class="line">        <span class="keyword">if</span> (REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">&quot;No MetadataConfig found, you must specify the remote Metadata Center address when &#x27;metadata=remote&#x27; is enabled.&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//取第一个元数据中心配置</span></span><br><span class="line">    MetadataReportConfig metadataReportConfig = metadataReportConfigs.iterator().next();</span><br><span class="line">    ConfigValidationUtils.validateMetadataConfig(metadataReportConfig);</span><br><span class="line">    <span class="keyword">if</span> (!metadataReportConfig.isValid()) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//执行元数据中心的初始化，这个init方法中主要是根据元数据中心配置的协议去创建对应的MetadataReport对象设置到用于或许将元数据上报写入到元数据中心</span></span><br><span class="line">    <span class="comment">//这一步主要是根据元数据中心配置的协议去创建对应的MetadataReport对象设置到MetadataReportInstance私有属性metadataReport中，后续可以通过MetadataReportInstance#getMetadataReport方法获取单例metadataReport将元数据上报写入到元数据中心</span></span><br><span class="line">    MetadataReportInstance.init(metadataReportConfig.toUrl());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="2-2-执行exportServices-方法循环导出服务"><a href="#2-2-执行exportServices-方法循环导出服务" class="headerlink" title="2.2 执行exportServices()方法循环导出服务"></a>2.2 执行exportServices()方法循环导出服务</h5><figure class="highlight java"><figcaption><span>DubboBootstrap.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">exportServices</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">//configManager中保存了所有的服务配置（添加操作查看1.3.2）</span></span><br><span class="line">    configManager.getServices().forEach(sc -&gt; &#123;</span><br><span class="line">        <span class="comment">//这个sc就是某个具体的服务了</span></span><br><span class="line">        ServiceConfig serviceConfig = (ServiceConfig) sc;</span><br><span class="line">        serviceConfig.setBootstrap(<span class="keyword">this</span>);</span><br><span class="line">        <span class="comment">//判断是否需通过线程池异步执行服务暴露操作</span></span><br><span class="line">        <span class="keyword">if</span> (exportAsync) &#123;</span><br><span class="line">            ExecutorService executor = executorRepository.getServiceExporterExecutor();</span><br><span class="line">            Future&lt;?&gt; future = executor.submit(() -&gt; &#123;</span><br><span class="line">                sc.export();</span><br><span class="line">                exportedServices.add(sc);</span><br><span class="line">            &#125;);</span><br><span class="line">            asyncExportingFutures.add(future);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">//执行具体服务暴露逻辑</span></span><br><span class="line">            sc.export();</span><br><span class="line">            <span class="comment">//将暴露成功的服务保存在exportedServices列表中</span></span><br><span class="line">            exportedServices.add(sc);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h6 id="2-2-1-执行ServiceConfig-export"><a href="#2-2-1-执行ServiceConfig-export" class="headerlink" title="2.2.1 执行ServiceConfig#export()"></a>2.2.1 执行ServiceConfig#export()</h6><figure class="highlight java"><figcaption><span>ServiceConfig.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">export</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!shouldExport()) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//bootstrap此处已经不为null了，在实例化监听器的时候就实例化过了</span></span><br><span class="line">    <span class="keyword">if</span> (bootstrap == <span class="keyword">null</span>) &#123;</span><br><span class="line">        bootstrap = DubboBootstrap.getInstance();</span><br><span class="line">        bootstrap.initialize();</span><br><span class="line">    &#125;</span><br><span class="line">    checkAndUpdateSubConfigs();</span><br><span class="line">    <span class="comment">//init serviceMetadata</span></span><br><span class="line">    serviceMetadata.setVersion(getVersion());</span><br><span class="line">    serviceMetadata.setGroup(getGroup());</span><br><span class="line">    serviceMetadata.setDefaultGroup(getGroup());</span><br><span class="line">    serviceMetadata.setServiceType(getInterfaceClass());</span><br><span class="line">    serviceMetadata.setServiceInterfaceName(getInterface());</span><br><span class="line">    serviceMetadata.setTarget(getRef());</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (shouldDelay()) &#123;</span><br><span class="line">        DELAY_EXPORT_EXECUTOR.schedule(<span class="keyword">this</span>::doExport, getDelay(), TimeUnit.MILLISECONDS);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">//执行服务导出</span></span><br><span class="line">        doExport();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//此方法中会发布ServiceConfigExportedEvent事件，ServiceNameMappingListener监听器会监听该事件往配置中心写入接口全限定名</span></span><br><span class="line">    exported();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><figcaption><span>ServiceConfig.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">doExport</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (unexported) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">&quot;The service &quot;</span> + interfaceClass.getName() + <span class="string">&quot; has already unexported!&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//已经有其他线程执行过导出该服务的操作则直接返回</span></span><br><span class="line">    <span class="keyword">if</span> (exported) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//设置已导出标识</span></span><br><span class="line">    exported = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (StringUtils.isEmpty(path)) &#123;</span><br><span class="line">        path = interfaceName;</span><br><span class="line">    &#125;</span><br><span class="line">    doExportUrls();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h6 id="2-2-2-执行ServiceConfig-doExportUrls"><a href="#2-2-2-执行ServiceConfig-doExportUrls" class="headerlink" title="2.2.2 执行ServiceConfig#doExportUrls()"></a>2.2.2 执行ServiceConfig#doExportUrls()</h6><figure class="highlight java"><figcaption><span>ServiceConfig.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">doExportUrls</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">//获取ServiceRepository实例，该实例在2中的ApplicationModel.initFrameworkExts();方法中被加载过了</span></span><br><span class="line">    ServiceRepository repository = ApplicationModel.getServiceRepository();</span><br><span class="line">    <span class="comment">//将服务接口包装成ServiceDescriptor对象添加到ServiceRepository#services Map中，key为接口全限定名，如果key已存在则不添加</span></span><br><span class="line">    ServiceDescriptor serviceDescriptor = repository.registerService(getInterfaceClass());</span><br><span class="line">    <span class="comment">//将上一步的serviceDescriptor加上ref等对象组合成ProviderModel对象添加到ServiceRepository#providers Map中，key为接口名称+组名称+版本，key已存在则不添加</span></span><br><span class="line">    repository.registerProvider(</span><br><span class="line">            getUniqueServiceName(),</span><br><span class="line">            ref,</span><br><span class="line">            serviceDescriptor,</span><br><span class="line">            <span class="keyword">this</span>,</span><br><span class="line">            serviceMetadata</span><br><span class="line">    );</span><br><span class="line">    <span class="comment">//这一步主要是将配置的注册中心列表组装成url列表（可配置多个注册中心），url格式如下：</span></span><br><span class="line">    <span class="comment">//registry://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=c3-provider&amp;dubbo=2.0.2&amp;pid=1868&amp;qos.enable=false&amp;registry=zookeeper&amp;release=2.7.8&amp;timestamp=1612088136201</span></span><br><span class="line">    <span class="comment">//这里有个地方需要注意，就是如果注册中心配置参数中有添加key为registry-type，value为service的参数，则就会使用service-discovery-registry协议（该协议对应的拓展实现是ServiceDiscoveryRegistryProtocol，该类继承自RegistryProtocol但重写了getRegistryUrl方法，会使得RegistryFactory拓展实现使用ServiceDiscoveryRegistryFactory，最终在服务导出3中获取到的Register对象为ServiceDiscoveryRegistry，从而达到修改注册粒度为应用的目的）</span></span><br><span class="line">    List&lt;URL&gt; registryURLs = ConfigValidationUtils.loadRegistries(<span class="keyword">this</span>, <span class="keyword">true</span>);</span><br><span class="line">    <span class="comment">//循环配置的协议列表，为每个协议都暴露服务，doExportUrlsFor1Protocol中还会循环registryURLs。所以dubbo服务暴露支持多协议多注册中心</span></span><br><span class="line">    <span class="keyword">for</span> (ProtocolConfig protocolConfig : protocols) &#123;</span><br><span class="line">        String pathKey = URL.buildKey(getContextPath(protocolConfig)</span><br><span class="line">                .map(p -&gt; p + <span class="string">&quot;/&quot;</span> + path)</span><br><span class="line">                .orElse(path), group, version);</span><br><span class="line">        repository.registerService(pathKey, interfaceClass);</span><br><span class="line">        serviceMetadata.setServiceKey(pathKey);</span><br><span class="line">        <span class="comment">//执行某种协议的暴露，同时传入了注册中心列表，同一种协议可以暴露到多个注册中心</span></span><br><span class="line">        doExportUrlsFor1Protocol(protocolConfig, registryURLs);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h6 id="2-2-3-执行ServiceConfig-doExportUrlsFor1Protocol"><a href="#2-2-3-执行ServiceConfig-doExportUrlsFor1Protocol" class="headerlink" title="2.2.3 执行ServiceConfig#doExportUrlsFor1Protocol()"></a>2.2.3 执行ServiceConfig#doExportUrlsFor1Protocol()</h6><p>这个doExportUrlsFor1Protocol方法中的代码比较多，经过精简后的代码如下</p>
<figure class="highlight java"><figcaption><span>ServiceConfig.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">doExportUrlsFor1Protocol</span><span class="params">(ProtocolConfig protocolConfig, List&lt;URL&gt; registryURLs)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//省略代码无数...，这部分省略的代码主要是收集相关参数添加到map中为后续生成Url对象做准备</span></span><br><span class="line">    <span class="comment">//获取暴露的主机，配置中没有指定的话一般是通过InetAddress.getLocalHost().getHostAddress()获取</span></span><br><span class="line">    String host = findConfigedHosts(protocolConfig, registryURLs, map);</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//获取暴露的端口，配置中没有指定的话获取的是DubboProtocol#DEFAULT_PORT 20880端口</span></span><br><span class="line">    Integer port = findConfigedPorts(protocolConfig, name, map);</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//组装成url对象，url格式如下（dubbo协议为例）</span></span><br><span class="line">    <span class="comment">//dubbo://192.168.56.1:20880/com.study.api.UserService?anyhost=true&amp;application=c3-provider&amp;bind.ip=192.168.56.1&amp;bind.port=20880&amp;default=true&amp;deprecated=false&amp;dubbo=2.0.2&amp;dynamic=true&amp;generic=false&amp;interface=com.study.api.UserService&amp;metadata-type=remote&amp;methods=getUserList&amp;pid=1868&amp;qos.enable=false&amp;release=2.7.8&amp;side=provider&amp;timestamp=1612088979247</span></span><br><span class="line">    URL url = <span class="keyword">new</span> URL(name, host, port, getContextPath(protocolConfig).map(p -&gt; p + <span class="string">&quot;/&quot;</span> + path).orElse(path), map);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//可通过自定义ConfiguratorFactory拓展来为url对象配置一些其它的参数</span></span><br><span class="line">    <span class="keyword">if</span> (ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class).hasExtension(url.getProtocol())) &#123;</span><br><span class="line">        url = ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class).getExtension(url.getProtocol()).getConfigurator(url).configure(url);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//取出url对象中的scope参数的值</span></span><br><span class="line">    String scope = url.getParameter(SCOPE_KEY);</span><br><span class="line">    <span class="comment">// 如果scope的值不为none，没做任何配置的时候scope会为null</span></span><br><span class="line">    <span class="keyword">if</span> (!SCOPE_NONE.equalsIgnoreCase(scope)) &#123;</span><br><span class="line">        <span class="comment">//如果scope不为remote则会执行本地暴露操作，本地暴露url格式如下（是新生产的url对象，不会去修改原先url对象中的协议）</span></span><br><span class="line">        <span class="comment">//injvm://127.0.0.1/com.study.api.UserService?anyhost=true&amp;application=c3-provider&amp;bind.ip=192.168.56.1&amp;bind.port=20880&amp;default=true&amp;deprecated=false&amp;dubbo=2.0.2&amp;dynamic=true&amp;generic=false&amp;interface=com.study.api.UserService&amp;metadata-type=remote&amp;methods=getUserList&amp;pid=1868&amp;qos.enable=false&amp;release=2.7.8&amp;side=provider&amp;timestamp=1612088979247</span></span><br><span class="line">        <span class="comment">//可以看到使用的是injvm协议，所以基于自适应拓展会使用InjvmExporter#export执行本地服务暴露操作，具体细节这里就不展开了，下面的远程暴露会涉及到</span></span><br><span class="line">        <span class="keyword">if</span> (!SCOPE_REMOTE.equalsIgnoreCase(scope)) &#123;</span><br><span class="line">            exportLocal(url);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//如果scope不为local则执行下面的远程暴露逻辑，即暴露到注册中心</span></span><br><span class="line">        <span class="keyword">if</span> (!SCOPE_LOCAL.equalsIgnoreCase(scope)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (CollectionUtils.isNotEmpty(registryURLs)) &#123;</span><br><span class="line">                <span class="keyword">for</span> (URL registryURL : registryURLs) &#123;</span><br><span class="line">                    <span class="comment">//如果配置的是injvm协议则不进行远程暴露，即使有配置注册中心</span></span><br><span class="line">                    <span class="keyword">if</span> (LOCAL_PROTOCOL.equalsIgnoreCase(url.getProtocol())) &#123;</span><br><span class="line">                        <span class="keyword">continue</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                    url = url.addParameterIfAbsent(DYNAMIC_KEY, registryURL.getParameter(DYNAMIC_KEY));</span><br><span class="line">                    URL monitorUrl = ConfigValidationUtils.loadMonitor(<span class="keyword">this</span>, registryURL);</span><br><span class="line">                    <span class="keyword">if</span> (monitorUrl != <span class="keyword">null</span>) &#123;</span><br><span class="line">                        url = url.addParameterAndEncoded(MONITOR_KEY, monitorUrl.toFullString());</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="comment">//这里主要是取出url中指定的代理工厂（key为proxy的值），如果有指定的话会添加到registryURL中供下面获取Invoker对象使用。没有指定默认会使用javassist作为代理</span></span><br><span class="line">                    String proxy = url.getParameter(PROXY_KEY);</span><br><span class="line">                    <span class="keyword">if</span> (StringUtils.isNotEmpty(proxy)) &#123;</span><br><span class="line">                        registryURL = registryURL.addParameter(PROXY_KEY, proxy);</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="comment">//首先会往registryURL中添加参数，key为export，值为编码后的url（就是上面dubbo开头的那个url）</span></span><br><span class="line">                    <span class="comment">//然后通过ProxyFactory自适应拓展执行getInvoker方法获取Invoker对象，registerURL中没有指定的代理则默认使用javassist代理</span></span><br><span class="line">                    <span class="comment">//JavassistProxyFactory#getInvoker方法返回一个AbstractProxyInvoker对象，该对象中重写了doInvoke方法（重写后的方法中对真实的服务对象进行了包装，在调用invoke方法的时候就是通过包装后的对象反射调用目标方法）</span></span><br><span class="line">                    Invoker&lt;?&gt; invoker = PROXY_FACTORY.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(EXPORT_KEY, url.toFullString()));</span><br><span class="line">                    <span class="comment">//通过装饰器模式将invoker和this对象委托给了DelegateProviderMetaDataInvoker对象</span></span><br><span class="line">                    DelegateProviderMetaDataInvoker wrapperInvoker = <span class="keyword">new</span> DelegateProviderMetaDataInvoker(invoker, <span class="keyword">this</span>);</span><br><span class="line">                    <span class="comment">//通过Protocol自适应拓展执行export方法进行暴露服务，此时Url的protocol值为registry，所以会先加载RegistryProtocol实例然后执行实例的export进行暴露服务</span></span><br><span class="line">                    <span class="comment">//RegistryProtocol实例在加载的时候会被QosProtocolWrapper（在线运维服务包装器），ProtocolFilterWrapper（过滤器调用链包装器），ProtocolListenerWrapper（协议监听器包装器）这三个类包装</span></span><br><span class="line">                    <span class="comment">//所以后续RegistryProtocol实例的export，refer，destroy，getServers等方法被调用的时候都会经过这三个包装器，执行顺序和上面包装顺序相反</span></span><br><span class="line">                    Exporter&lt;?&gt; exporter = PROTOCOL.export(wrapperInvoker);</span><br><span class="line">                    exporters.add(exporter);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                Invoker&lt;?&gt; invoker = PROXY_FACTORY.getInvoker(ref, (Class) interfaceClass, url);</span><br><span class="line">                DelegateProviderMetaDataInvoker wrapperInvoker = <span class="keyword">new</span> DelegateProviderMetaDataInvoker(invoker, <span class="keyword">this</span>);</span><br><span class="line">                Exporter&lt;?&gt; exporter = PROTOCOL.export(wrapperInvoker);</span><br><span class="line">                exporters.add(exporter);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">//在前面省略的代理中有判断如果metadataReportConfig配置不为null则会完url中添加metadata-type参数值为remote，所有这个地方获取到的是RemoteWritableMetadataService</span></span><br><span class="line">            WritableMetadataService metadataService = WritableMetadataService.getExtension(url.getParameter(METADATA_KEY, DEFAULT_METADATA_STORAGE_TYPE));</span><br><span class="line">            <span class="keyword">if</span> (metadataService != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">//这一步会将当前接口服务的元数据写入到远程元数据中心</span></span><br><span class="line">                metadataService.publishServiceDefinition(url);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">this</span>.urls.add(url);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>至此代码调用就执行到了RegistryProtocol#export方法，该方法中会进行服务启动暴露及注册到注册中心，这两部分的具体逻辑见后面分析</p>
<link rel="stylesheet" href="/css/spoiler.css" type="text/css"><script src="/js/spoiler.js" type="text/javascript" async></script> 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://luobiao320.gitee.io/dubbo/springboot%E4%B8%ADdubbo%E6%9C%8D%E5%8A%A1%E5%AF%BC%E5%87%BA-1/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/dubbo/" rel="tag">dubbo</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/springboot/" rel="tag">springboot</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E6%9C%8D%E5%8A%A1%E5%AF%BC%E5%87%BA/" rel="tag">服务导出</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/dubbo/springboot%E4%B8%ADdubbo%E6%9C%8D%E5%8A%A1%E5%AF%BC%E5%87%BA-2/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            springboot中dubbo服务导出-2
          
        </div>
      </a>
    
    
      <a href="/dubbo/dubbo%E6%9C%8D%E5%8A%A1%E8%87%AA%E7%9C%81/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">dubbo服务自省</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "kHx6wceVXdEyiCrLm0sLAwoF-gzGzoHsz",
    app_key: "ArEdGk6wzHOhrXLiwmClhDNH",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2020-2021
        <i class="ri-heart-fill heart_icon"></i> luobiao
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        Powered by <a href="https://hexo.io" target="_blank">Hexo</a>
        <span class="division">|</span>
        Theme - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      
        <li>
          <a href="http://beian.miit.gov.cn/" target="_black" rel="nofollow">赣ICP备2020014719号-1</a>
        </li>
        
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="http://img.luobiao.vip/53119d0bda706bbe350333137a67ea3e_1.jpg" alt="一曲秋殇"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/dubbo">dubbo</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/spring">spring</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/mysql">mysql</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->

<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>